<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8" style="width: 100%;">
      <el-steps 
        :active="currentStep" 
        process-status="finish"
        finish-status="success" 
        simple 
        style="width: 100%; padding: 20px; background: linear-gradient(to right, #f8f9fa, #e9ecef); border-radius: 8px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);"
        active-color="#409EFF"
      >
        <el-step title="选择货架" icon="Goods" />
        <el-step title="选择订单" icon="Document" />
        <el-step title="选择原片" icon="Picture" />
        <el-step title="设置参数" icon="Setting" />
        <el-step title="开始优化" icon="Finished" />
      </el-steps>
    </el-row>

    <div class="shelf-container" v-show="currentStep == 0">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" default icon="Edit" @click="handleShelfImport">批量导入货架</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleShelfAdd">新增</el-button>
        </el-col>

        <el-col :span="1.5" class="right-align-col">
          <el-button 
            type="primary" 
            plain 
            icon="ArrowLeft" 
            @click="handlePrevious"
            :disabled="currentStep == 0"
            class="navigation-btn prev-btn">上一步</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button 
            type="success" 
            default 
            icon="CircleCheck" 
            @click="handleNext"
            class="navigation-btn next-btn">确定</el-button>
        </el-col>
      </el-row>


      <!-- 货架选择和编辑列表 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch"
        label-width="68px">
        <el-form-item label="货架名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入货架名称" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="剩余数量" prop="beginLeftNumber" span="6">
          <el-input v-model="queryParams.beginLeftNumber" placeholder="请输入剩余数量下限" @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="" prop="endLeftNumber" span="6">
          <el-input v-model="queryParams.endLeftNumber" placeholder="请输入剩余数量上限" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="最大片数" prop="beginMaxPiecesNumber">
          <el-input v-model="queryParams.beginMaxPiecesNumber" placeholder="请输入最大片数下限" @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="" prop="endMaxPiecesNumber">
          <el-input v-model="queryParams.endMaxPiecesNumber" placeholder="请输入最大片数上限" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          <el-button type="primary" icon="Search" @click="handleQuery">筛选</el-button>
        </el-form-item>
      </el-form>


      <!-- 货架选择和编辑列表 -->
      <el-table v-loading="loading" :data="shelfList" stripe @selection-change="handleSelectionChange"
        @sort-change="handleSortChange" >
        <el-table-column label="货架名称" align="center" sortable="custom" prop="name" />
        <el-table-column label="剩余数量(架)" align="center" sortable="custom" prop="leftNumber" />
        <el-table-column label="最大片数(片)" align="center" sortable="custom" prop="maxPiecesNumber" />
        <el-table-column label="最大总面积 (mm²)" align="center" sortable="custom" prop="maxArea" />
        <el-table-column label="最大总重量(kg)" align="center" sortable="custom" prop="maxTotalWeight" />
        <el-table-column label="总厚度(mm)" align="center" sortable="custom" prop="thickness" />
        <el-table-column label="最大长边差(mm)" align="center" sortable="custom" prop="maxLongSideDiff" width="150" />
        <el-table-column label="最大短边差(mm)" align="center" sortable="custom" prop="maxShortSideDiff" width="150" />
        <el-table-column label="最大不同规格" align="center" sortable="custom" prop="maxDiffSpec" />
        <el-table-column label="优先级" align="center" sortable="custom" prop="priority" width="150">
          <template #header>
            <div style="display: flex; align-items: center; justify-content: center;">
              <span>优先级</span>
              <el-tooltip content="优先级按数值大小排序，1是最高优先级" placement="top">
                <el-icon style="margin-left: 5px; cursor: help;"><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <template #default="scope">
            <el-input-number v-model="scope.row.priority" placeholder="请输入优先级" :min='1' size="small" />
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" show-overflow-tooltip width="300"
          class-name="small-padding fixed-width">
          <template #default="scope">
            <el-select v-model="scope.row.status" placeholder="请选择状态" size="small" style="width:30%;"
              @change="handleStatusChange(scope.row)" required>
              <el-option label="使用" value="1" />
              <el-option label="不使用" value="0" :default="true" />
            </el-select>
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />

      <!-- 添加或修改货架对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body :center="true">
        <el-form ref="shelfRef" :model="form" :rules="rules" label-width="150px">
          <el-form-item label="货架名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入货架名称" />
          </el-form-item>
          <el-form-item label="剩余数量" prop="leftNumber">
            <el-input v-model="form.leftNumber" placeholder="请输入剩余数量" type="number" />
          </el-form-item>
          <el-form-item  label="最大片数" prop="maxPiecesNumber">
            <el-input v-model="form.maxPiecesNumber" placeholder="请输入最大片数" type="number" />
          </el-form-item>
          <el-form-item  label="最大总面积(mm²)" prop="maxArea">
            <el-input v-model="form.maxArea" placeholder="请输入最大总面积" type="number" />
          </el-form-item>
          <el-form-item  label="最大总重量(kg)" prop="maxTotalWeight">
            <el-input v-model="form.maxTotalWeight" placeholder="请输入最大总重量" type="number" />
          </el-form-item>
          <el-form-item  label="最大长边差(mm)" prop="maxLongSideDiff">
            <el-input v-model="form.maxLongSideDiff" placeholder="请输入最大长边差" type="number" />
          </el-form-item>
          <el-form-item  label="最大短边差(mm)" prop="maxShortSideDiff">
            <el-input v-model="form.maxShortSideDiff" placeholder="请输入最大短边差" type="number" />
          </el-form-item>
          <el-form-item  label="最大不同规格" prop="maxDiffSpec">
            <el-input v-model="form.maxDiffSpec" placeholder="请输入最大不同规格" type="number" />
          </el-form-item>
          <el-form-item  label="总厚度(mm)" prop="thickness">
            <el-input v-model="form.thickness" placeholder="请输入总厚度" type="number" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer" style="text-align: center;">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 批量导入货架对话框 -->
      <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
        <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
          :on-progress="handleShelfFileUploadProgress" :on-success="handleShelfFileSuccess" :auto-upload="false" drag>
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip text-center">
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="importShelfTemplate">下载模板</el-link>
            </div>
          </template>
        </el-upload>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>

    </div>

    <div  v-show="currentStep == 1">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleOrderImport" >批量导入订单</el-button>
        </el-col>
        <el-col :span="11">
 
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Monitor" @click="handleOrderAutoShelf">自动分架</el-button>
          <el-button type="primary" plain icon="Monitor" @click="getRequirementList">默认分架</el-button>
          <el-button type="success" plain icon="Monitor" @click="oneBoxShelf">单箱单架</el-button>
        </el-col>
        <el-col :span="1.5" class="right-align-col">
          <el-button 
            type="primary" 
            plain 
            icon="ArrowLeft" 
            @click="handlePrevious"
            :disabled="currentStep == 0"
            class="navigation-btn prev-btn">上一步</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button 
            type="success" 
            default 
            icon="CircleCheck" 
            @click="handleNext"
            class="navigation-btn next-btn">确定</el-button>
        </el-col>
      </el-row>
      <!-- 订单选择和编辑列表 -->
      <el-row>
        <el-col :span="12">
        <el-form :model="queryOrderParams" ref="queryOrderRef" :inline="true"
          v-show="showOrderSearch" label-width="68px">
          <el-form-item label="订单名称" prop="name">
            <el-input v-model="queryOrderParams.name" placeholder="请输入订单名称" @keyup.enter="handleOrderQuery"
              style="width: 120px" />
          </el-form-item>

          <el-form-item label="厚度" prop="beginThickness">
            <el-input v-model="queryOrderParams.beginThickness" placeholder="请输入厚度下限" @keyup.enter="handleOrderQuery"
              style="width: 120px" />
          </el-form-item>
          <el-form-item label="" prop="endThickness">
            <el-input v-model="queryOrderParams.endThickness" placeholder="请输入厚度上限" @keyup.enter="handleOrderQuery"
              style="width: 120px" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleOrderQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetOrderQuery">重置</el-button>
          </el-form-item>


          <el-table v-loading="orderLoading" :data="orderList" @sort-change="handleOrderSortChange"
            :row-class-name="tableRowClassName">
            <el-table-column label="订单名称" align="center" sortable="custom" prop="name" />
            <el-table-column label="总片数" align="center" sortable="custom" prop="piecesNumber" />
            <el-table-column label="总箱数" align="center" sortable="custom" prop="boxesNumber" />
            <el-table-column label="厚度(mm)" align="center" sortable="custom" prop="thickness" />
            <el-table-column label="最小面积(mm²)" align="center" sortable="custom" prop="minArea" />
            <el-table-column label="最大面积(mm²)" align="center" sortable="custom" prop="maxArea" />
            <el-table-column label="颜色" align="center" sortable="custom" prop="color" />
            <el-table-column label="操作" align="center" show-overflow-tooltip width="200px"
              class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button link type="primary" icon="select" @click="handleOrderUpdate(scope.row)"
                  >{{ selectedOrderIdList.indexOf(scope.row.id) !== -1 ? '取消' :
                    '选择' }}</el-button>
                <el-button link type="primary" icon="Delete" @click="handleOrderDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="orderTotal > 0" :total="orderTotal" v-model:page="queryOrderParams.pageNum"
            v-model:limit="queryOrderParams.pageSize" @pagination="getOrderList" />
        </el-form>
      </el-col>


      <el-col :span="1">
      </el-col>

      <el-col :span="11">
        <el-form :model="queryRequirementParams" ref="queryRequirementRef" :inline="true"
          v-show="showOrderSearch" label-width="68px">



          <el-table 
            ref="requirementTable"
            v-loading="orderLoading" 
            :data="requirementList" 
            :row-class-name="requirementRowClassName"
            height="700px"
            :cell-style="{ padding: '1px 0' }">
            <el-table-column label="片数" align="center" prop="piecesNumber" />
            <el-table-column label="箱名称" align="center" prop="boxName" />
            <el-table-column label="长度(mm)" align="center" prop="length" />
            <el-table-column label="宽度(mm)" align="center" prop="width" />
            <el-table-column label="架类型" align="center" prop="shelfId">
              <template #default="scope">
                <el-select v-model="scope.row.shelfId" placeholder="请选择架类型"
                  @change="handleShelfTypeChange(scope.$index)">
                  <el-option v-for="item in shelfList" :key="item.id" :label="item.name" :value="item.id" disabled>
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="架号" align="center" prop="shelfNum">
              <template #default="scope">
                <el-input v-model.number="scope.row.shelfNum" placeholder="请输入架号" type="number"
                  @input="handleShelfNumberInput(scope.$index)" />
              </template>
            </el-table-column>
            <el-table-column label="架内序" align="center" prop="shelfOrder">
              <template #default="scope">
                <el-input v-model.number="scope.row.shelfOrder" placeholder="请输入架内序" type="number"
                  @input="handleShelfIndexInput(scope.$index)" />
              </template>
            </el-table-column>
          </el-table>
          <!-- <pagination v-show="requirementTotal > 0" :total="requirementTotal" v-model:page="queryRequirementParams.pageNum"
              v-model:limit="queryRequirementParams.pageSize" @pagination="getRequirementList" /> -->
        </el-form>
      </el-col>

    </el-row>
    <!-- </div>
  </div> -->


    <!-- 批量导入订单对话框 -->

    <el-dialog :title="orderUpload.title" v-model="orderUpload.open" width="400px" append-to-body>
      <el-form :model="orderUpload" label-width="100px">
        <el-form-item label="厚度(mm)" required>
          <el-input v-model="orderUpload.thickness" placeholder="请输入厚度" type="number" />
          <div class="thick-buttons">
            <el-button 
              v-for="thickness in settingThicknessList" 
              :key="thickness"
              size="small"
              @click="orderUpload.thickness = thickness"
              :style="{ backgroundColor: getRandomColor() }"
            >
              {{ thickness }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="颜色" required>
          <el-input v-model="orderUpload.color" placeholder="请输入颜色" />
          <div class="color-buttons">
            <el-button 
              v-for="color in settingColorList" 
              :key="color"
              size="small"
              @click="orderUpload.color = color"
              :style="{ backgroundColor: getRandomColor() }"
            >
              {{ color }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls"
        :action="orderUpload.url + '?updateSupport=' + orderUpload.updateSupport + '&thickness=' + orderUpload.thickness + '&color=' + orderUpload.color"
        enctype="multipart/form-data" :headers="orderUpload.headers" :disabled="orderUpload.isUploading"
        :on-progress="handleOrderFileUploadProgress" :on-success="handleOrderFileSuccess" :on-exceed="handleOrderExceed"
        :on-change="handleOrderChange" :fileList="orderFileList" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="importOrderTemplate">下载模板</el-link>
          </div>
        </template>

      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitOrderFileForm">确 定</el-button>
          <el-button @click="orderUpload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>


  <!-- 原片选择和编辑列表 -->
  <div  v-show="currentStep == 2">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleOriginalImport"
       >批量导入原片</el-button>
      </el-col>

      <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleOriginalAdd">新增原片</el-button>
        </el-col>

      <el-col :span="1.5" class="right-align-col">
          <el-button 
            type="primary" 
            plain 
            icon="ArrowLeft" 
            @click="handlePrevious"
            :disabled="currentStep == 0"
            class="navigation-btn prev-btn">上一步</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button 
            type="success" 
            default 
            icon="CircleCheck" 
            @click="handleNext"
            class="navigation-btn next-btn">确定</el-button>
        </el-col>
 
    </el-row>

    <el-form :model="queryOriginalParams" ref="queryOriginalRef" :inline="true" v-show="showOriginalSearch" label-width="68px">
      <el-form-item label="批次" prop="batch">
        <el-input
          v-model="queryOriginalParams.batch"
          placeholder="请输入批次"
          @keyup.enter="handleOriginalQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-input
          v-model="queryOriginalParams.type"
          placeholder="请输入类型"
          @keyup.enter="handleOriginalQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="宽度" prop="beginWidth">
        <el-input
          v-model="queryOriginalParams.beginWidth"
          placeholder="请输入宽度下限"
          @keyup.enter="handleOriginalQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="" prop="endWidth">
        <el-input
          v-model="queryOriginalParams.endWidth"
          placeholder="请输入宽度上限"
          @keyup.enter="handleOriginalQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="高度" prop="beginLength">
        <el-input
          v-model="queryOriginalParams.beginLength"
          placeholder="请输入高度下限"
          @keyup.enter="handleOriginalQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="" prop="endLength">
        <el-input
          v-model="queryOriginalParams.endLength"
          placeholder="请输入高度上限"
          @keyup.enter="handleOriginalQuery"
          style="width: 120px"
        />
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleOriginalQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetOriginalQuery">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="selectOriginalAll" @change="selectOriginalAllChange" label="全选" />
    </el-form-item>
    
    </el-form>

    <el-table v-loading="originalLoading" :data="originalList" @selection-change="handleOriginalSelectionChange" 
    @sort-change="handleOriginalSortChange">
      <!-- <el-table-column label="批次" align="center" sortable="custom" prop="batch" /> -->
      <el-table-column label="类型" align="center" sortable="custom" prop="type" />
      <el-table-column label="厚度(mm)" align="center" sortable="custom" prop="thickness" />
      <el-table-column label="颜色" align="center" sortable="custom" prop="color" />
      <el-table-column label="宽度(mm)" align="center" sortable="custom" prop="width" />
      <el-table-column label="高度(mm)" align="center" sortable="custom" prop="length" />
      <el-table-column label="优先级" align="center" sortable="custom" prop="priority" width="200">
          <template #header>
            <div style="display: flex; align-items: center; justify-content: center;">
              <span>优先级</span>
              <el-tooltip content="优先级按数值大小排序，1是最高优先级" placement="top">
                <el-icon style="margin-left: 5px; cursor: help;"><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <template #default="scope">
            <el-input-number v-model="scope.row.priority" placeholder="请输入优先级" :min='1' size="small" />
          </template>
        </el-table-column>
      <el-table-column label="操作" align="center"  class-name="small-padding fixed-width">
        <template #default="scope">
          <el-select  
            v-model="scope.row.status" 
            placeholder="请选择状态"  
            size="small" 
            @change="handleOriginalSelectChanged(scope.row)" 
            style="width:60%;"
            :default-first-option="true">
            <el-option label="使用" value="1" />
            <el-option label="不使用" value="0" />
          </el-select>
          <el-button link type="primary" icon="Delete" @click="handleOriginalDelete(scope.row)">删除</el-button>
        </template>

      </el-table-column>
    </el-table>
    
    <pagination
      v-show="originalTotal>0"
      :total="originalTotal"
      v-model:page="queryOriginalParams.pageNum"
      v-model:limit="queryOriginalParams.pageSize"
      @pagination="getOriginalList"
    />

    <!-- 添加或修改原片对话框 -->
    <el-dialog :title="originalTitle" v-model="originalOpen" width="500px" append-to-body>
      <el-form ref="originalRef" :model="originalForm" :rules="originalRules" label-width="auto">
        <el-form-item label="类型" prop="type" required>
          <el-input v-model="originalForm.type" placeholder="请输入类型" />
        </el-form-item>
        <el-form-item label="数量" prop="availableNumber" required>
          <el-input v-model="originalForm.availableNumber" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="宽度(mm)" prop="width" required>
          <el-input v-model="originalForm.width" placeholder="请输入宽度" />
        </el-form-item>
        <el-form-item label="高度(mm)" prop="length">
          <el-input v-model="originalForm.length" placeholder="请输入高度" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleOriginalSubmit">确 定</el-button>
          <el-button @click="originalCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

          <!-- 批量导入对话框 -->
    <el-dialog :title="originalUpload.title" v-model="originalUpload.open" width="400px" append-to-body>
         <el-upload
            ref="originalUploadRef"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="originalUpload.headers"
            :action="originalUpload.url + '?updateSupport=' + originalUpload.updateSupport + '&thickness=' + originalUpload.thickness + '&color=' + originalUpload.color"
            :disabled="originalUpload.isUploading"
            :on-progress="handleOriginalFileUploadProgress"
            :on-success="handleOriginalFileSuccess"
            :auto-upload="false"
            drag
         >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" style="color: #E6A23C; font-size: 12px;">
               注意：导入成功后只会显示与当前订单颜色和厚度相同的原片数据
            </div>
            <template #tip>
               <div class="el-upload__tip text-center">
                  <span>仅允许导入xls、xlsx格式文件。</span>
                  <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="importOriginalTemplate">下载模板</el-link>
               </div>
            </template>
         </el-upload>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitOriginalFileForm">确 定</el-button>
               <el-button @click="originalUpload.open = false">取 消</el-button>
            </div>
         </template>
      </el-dialog>
  </div>

  <!-- 优化参数设置 -->
  <div v-show="currentStep == 3">

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" default icon="Edit" @click="handlePackageImport"
          v-hasPermi="['order:shelf:edit']">导入优化包</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleExport"
          v-hasPermi="['order:shelf:add']">导出优化包</el-button>
      </el-col> -->

      <el-col :span="1.5" class="right-align-col">
          <el-button 
            type="primary" 
            plain 
            icon="ArrowLeft" 
            @click="handlePrevious"
            :disabled="currentStep == 0"
            class="navigation-btn prev-btn">上一步</el-button>
        </el-col>
      <el-col :span="1.5" >
        <el-button 
          type="success" 
          default 
          icon="CircleCheck" 
          @click="handleNext"
          class="navigation-btn next-btn">开始优化</el-button>
      </el-col>
    </el-row>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1">

      </el-col>
      <el-col :span="6">
        <el-container>
          <el-header height="50px" class="custom-header">切割参数</el-header>
        </el-container>
        <el-main style="border: 1px solid #e4e7ed; border-radius: 0 0 8px 8px; background-color: #fff; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);">
          <el-row class="centered-col">
            <el-col :span="12">
              <div>磨边量(mm)</div>
            </el-col>
            <el-col :span="12" style="background-color: chartreuse;">
              <el-input v-model="paramConfig.grind"></el-input>
            </el-col>
          </el-row>
          <el-row class="centered-col">
            <el-col :span="12">
              <div>掰边距(mm)</div>
            </el-col>
            <el-col :span="12">
              <el-input 
                v-model="paramConfig.minWaste"
                @change="handleMinWasteChange"
              ></el-input>
            </el-col>
          </el-row>
          <el-row v-if="showMinWasteAlert" class="centered-col">
            <el-col :span="24">
              <el-alert 
                title="掰边距小于设定值最小值10" 
                type="warning" 
                @close="showMinWasteAlert = false" 
                style="width: 100%;"
              />
            </el-col>
          </el-row>
          <el-row class="centered-col">
            <el-col :span="12">
              <div>最大刀距-X(mm)</div>
            </el-col>
            <el-col :span="12" style="background-color: chartreuse;">
              <el-input v-model="paramConfig.max1Cut"></el-input>
            </el-col>
          </el-row>
          <el-row class="centered-col">
            <el-col :span="12">
              <div>最小刀距-X(mm)</div>
            </el-col>
            <el-col :span="12" style="background-color: chartreuse;">
              <el-input v-model="paramConfig.min1Cut"></el-input>
            </el-col>
          </el-row>
          <el-row class="centered-col">
            <el-col :span="12">
              <div>最小刀距-Y(mm)</div>
            </el-col>
            <el-col :span="12" style="background-color: chartreuse;">
              <el-input v-model="paramConfig.min2Cut"></el-input>
            </el-col>
          </el-row>
          <el-row class="centered-col">
            <el-col :span="12">
              <div>最小刀距-XZ(mm)</div>
            </el-col>
            <el-col :span="12" style="background-color: chartreuse;">
              <el-input v-model="paramConfig.min13Cut"></el-input>
            </el-col>
          </el-row>
          <el-row class="centered-col">
            <el-col :span="12">
              <div>原片修边量-左(mm)</div>
            </el-col>
            <el-col :span="12" style="background-color: chartreuse;">
              <el-input v-model="paramConfig.trimLeft"></el-input>
            </el-col>
          </el-row>
          <el-row class="centered-col">
            <el-col :span="12">
              <div>原片修边量-右(mm)</div>
            </el-col>
            <el-col :span="12" style="background-color: chartreuse;">
              <el-input v-model="paramConfig.trimRight"></el-input>
            </el-col>
          </el-row>
          <el-row class="centered-col">
            <el-col :span="12">
              <div>原片修边量-上(mm)</div>
            </el-col>
            <el-col :span="12" style="background-color: chartreuse;">
              <el-input v-model="paramConfig.trimTop"></el-input>
            </el-col>
          </el-row>
          <el-row class="centered-col">
            <el-col :span="12">
              <div>原片修边量-下(mm)</div>
            </el-col>
            <el-col :span="12" style="background-color: chartreuse;">
              <el-input v-model="paramConfig.trimBottom"></el-input>
            </el-col>
          </el-row>
        </el-main>
      </el-col>
      <el-col :span="6">
        <el-container>
          <el-header height="50px" class="custom-header">架序及其他参数</el-header>
        </el-container>
        <el-main style="border: 1px solid #e4e7ed; border-radius: 0 0 8px 8px; background-color: #fff; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05)">
          <el-row class="centered-col">
            <el-col :span="12">
              <div>通刀约束</div>
            </el-col>
            <el-col :span="12">
              <el-switch v-model="paramConfig.throughCut" disabled />
            </el-col>
          </el-row>
          <el-row class="centered-col">
            <el-col :span="12">
              <div>切割树深度</div>
            </el-col>
            <el-col :span="12">
              <el-select v-model="paramConfig.treeDepth" placeholder="请选择" size="default" style="width:100%;">
                <el-option label="6" value="1" />
              </el-select>
            </el-col>
          </el-row>
          <el-row class="centered-col">
            <el-col :span="12">
              <div>按箱按序</div>
            </el-col>
            <el-col :span="12">
              <el-switch v-model="paramConfig.isOffline" :active-value="1" :inactive-value="0" @change="handleBoxOrderChange" />
            </el-col>
          </el-row>
          <el-row class="centered-col">
            <el-col :span="12">
              <div>成品开架数</div>
            </el-col>
            <el-col :span="12" style="background-color: chartreuse;">
              <el-input v-model="paramConfig.maxShelf" :disabled="paramConfig.isOffline==0"></el-input>
            </el-col>
          </el-row>
          <el-row class="centered-col">
            <el-col :span="12">
              <div>输出反切</div>
            </el-col>
            <el-col :span="12">
                <el-switch v-model="paramConfig.cutReverse" :active-value="1" :inactive-value="0" />
            </el-col>
          </el-row>
          <el-row class="centered-col">
            <el-col :span="12">
              <div>余料长</div>
            </el-col>
            <el-col :span="12"  >
              <el-input v-model="paramConfig.tailLength" placeholder="请输入余料长" />
            </el-col>
          </el-row>
          <el-row class="centered-col">
            <el-col :span="12">
              <div>余料宽</div>
            </el-col>
            <el-col :span="12"  >
              <el-input v-model="paramConfig.tailWidth" placeholder="请输入余料宽"  />
            </el-col>
          </el-row>
        </el-main>
      </el-col>
      <el-col :span="11">
      
        <el-row>
          <el-col>
          <el-container>
            <el-header height="50px" class="custom-header">原片列表</el-header>
          </el-container>
          <el-main style="height: 250px; border: 1px solid #e4e7ed; border-radius: 0 0 8px 8px; background-color: #fff; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05)">
       
              <el-table v-loading="loading" :data="containedOriginalList">
                <el-table-column label="批次" align="center" prop="batch" />
                <el-table-column label="宽度(mm)" align="center" prop="width" />
                <el-table-column label="高度(mm)" align="center" prop="length" />
                <el-table-column label="厚度(mm)" align="center" prop="thickness" />
                <el-table-column label="优先级" align="center" prop="priority" />
              </el-table>
         
            <el-col>
              <pagination v-show="originalTotal > 0" :total="originalTotal" v-model:page="queryOriginalParams.pageNum"
                v-model:limit="queryOriginalParams.pageSize" @pagination="getOriginalList" />
            </el-col>
          </el-main>
        </el-col>
        </el-row>
        <!-- INSERT_YOUR_CODE -->
        <div style="height: 50px;"></div>
        <el-row>  
          <el-col>
          <el-container>
            <el-header height="50px" class="custom-header">订单列表</el-header>
          </el-container>
          <el-main style="height: 250px; border: 1px solid #e4e7ed; border-radius: 0 0 8px 8px; background-color: #fff; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05)">
         
              <el-table v-loading="loading" :data="containedOrderList">
                <el-table-column label="订单名称" align="center" prop="name" />
                <el-table-column label="总片数" align="center" prop="piecesNumber" />
                <el-table-column label="总箱数" align="center" prop="boxesNumber" />
                <el-table-column label="最小面积(mm²)" align="center" prop="minArea" />
                <el-table-column label="最大面积(mm²)" align="center" prop="maxArea" />
              </el-table>
           
            <el-col>
              <pagination v-show="orderTotal > 0" :total="orderTotal" v-model:page="queryOrderParams.pageNum"
                v-model:limit="queryOrderParams.pageSize" @pagination="getOrderList" />
            </el-col>
          </el-main>
        </el-col>
        </el-row>
      </el-col>
    </el-row>

  </div>
  </div>
</template>

<script setup name="Shelf">
import { getToken } from "@/utils/auth";
import { listShelf, getShelf, delShelf, addShelf, updateShelf } from "@/api/order/shelf";


const { proxy } = getCurrentInstance();

const shelfList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const router = useRouter();
const selectedShelvesIds = ref([]);

const currentStep = ref(0);

/*** 货架导入参数 */
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题（批量导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/order/shelf/importData"
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    name: null,
    beginLeftNumber: null,
    endLeftNumber: null,
    beginMaxPiecesNumber: null,
    endMaxPiecesNumber: null,
    isAsc: null,
    orderByColumn: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询货架选择和编辑列表 */
function getList() {
  loading.value = true;
  listShelf(queryParams.value).then(response => {
    shelfList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    shelfList.value.forEach(item => {
      item.priority = item.priority || 1;
      if (selectedShelvesIds.value.includes(item.id)) {
        item.status = '1';
      } else {
        item.status = '0';
      }
    });

  });
  
}

/** 下载货架模板操作 */
function importShelfTemplate() {
  proxy.download("order/shelf/importTemplate", {
  }, `shelf_template_${new Date().getTime()}.xlsx`);
};

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    leftNumber: null,
    maxPiecesNumber: null,
    maxArea: null,
    maxTotalWeight: null,
    maxLongSideDiff: null,
    maxShortSideDiff: null,
    maxDiffSpec: null,
    createTime: null,
    createrId: null,
    isAsc: null,
    orderByColumn: null
  };
  proxy.resetForm("shelfRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleShelfAdd() {
  reset();
  open.value = true;
  title.value = "添加货架";
}

/** 批量导入操作 */
function handleShelfImport() {
  upload.title = "用户导入";
  upload.open = true;
}

/** 检查配置 */
function checkConfig() {
  if(paramConfig.value.maxShelf === null || paramConfig.value.maxShelf === undefined || paramConfig.value.maxShelf < 1) {
    proxy.$modal.msgError("成品开架数不能为空");
    return false;
  }
  return true;
}

/** 检查货架选择 */
function checkShelfSelection() {
  if (selectedShelvesIds.value.length == 0) {
    proxy.$modal.msgError("请选择至少一个货架");
    return false;
  }
  return true;
}

/** 检查原片选择 */
function checkOriginalSelection() {
  if (selectOriginalIds.value.length == 0) {
    proxy.$modal.msgError("请选择至少一种原片");
    return false;
  }
  return true;
}
/** 检查订单选择 */
function checkOrderSelection() {
  if (selectedOrderIdList.value.length == 0) {
    proxy.$modal.msgError("请选择至少一个订单");
    return false;
  }

  const uniqueThicknessList = [...new Set(selectedOrderThicknessList.value)];
  if (uniqueThicknessList.length > 1) {
    proxy.$modal.msgError("只能选择一种厚度的订单");
    return false;
  }

  const uniqueColorList = [...new Set(selectedOrderColorList.value)];
  if (uniqueColorList.length > 1) {
    proxy.$modal.msgError("只能选择一种颜色的订单");
    return false;
  }
  return true;
}

/** 检查分架信息完整性 */
function checkShelfAssignment() {
  const errorRows = new Set();
  let firstErrorIndex = -1;
  for (let i = 0; i < requirementList.value.length; i++) {
    const item = requirementList.value[i];
    if (item.shelfId === null || item.shelfNum === null || item.shelfOrder === null || 
        item.shelfId === '' || item.shelfNum === '' || item.shelfOrder === ''||
        item.shelfId === undefined || item.shelfNum === undefined || item.shelfOrder === undefined) {
      errorRows.add(item.id);
      if (firstErrorIndex === -1) {
        firstErrorIndex = i;
      }
    }
  }

  if (errorRows.size > 0) {
    highlightErrorRows(errorRows);

    const requirementTable = proxy.$refs.requirementTable;
    if (requirementTable) {
      // 使用 nextTick 确保 DOM 更新后再滚动
      nextTick(() => {
        requirementTable.scrollTo({
          top: firstErrorIndex * 40, // 假设每行高度为40px
          behavior: 'smooth'
        });
      });
    }
    return false;
  }
  return true;
}

/** 高亮显示错误行 */
function highlightErrorRows(errorRows) {
  requirementList.value = requirementList.value.map(item => ({
    ...item,
    errorHighlight: errorRows.has(item.id)
  }));

  proxy.$modal.msgError("请完成所有分架后，再进行下一步");

  setTimeout(() => {
    requirementList.value = requirementList.value.map(item => ({
      ...item,
      errorHighlight: false
    }));
  }, 3000);
}

/** 处理第一步 */
function handleStepOne() {
  if (!checkShelfSelection()) return false;
  getOrderList(false);
  return true;
}

/** 处理第二步 */
function handleStepTwo() {
  if (!checkOrderSelection()) return false;
  if (!checkShelfAssignment()) return false;
  
  getOriginalList();
  return true;
}

/** 处理第三步 */
function handleStepThree() {
  if (!checkOriginalSelection()) return false;

  getProcessList()
  getContainedOrderList();
  getContainedOriginalList();
  return true;
}

/** 处理第四步 */
function handleStepFour() {
  if (!checkConfig()) return false;

  paramConfig.value.glassRequirements = requirementList.value
  paramConfig.value.glassOriginals = originalList.value.filter(item => item.status == 1)
  paramConfig.value.thickness = selectedOrderThicknessList.value[0]||null;
  paramConfig.value.color = selectedOrderColorList.value[0]||null;
  paramConfig.value.shelfId = selectedShelvesIds.value[0]||null;
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  const randomNum = Math.floor(10 + Math.random() * 90); // 生成两位随机数
  paramConfig.value.name = `${year}${month}${day}${hours}${minutes}${seconds}${randomNum}`;
  paramConfig.value.type = 1;
  addPackage(paramConfig.value).then(response => {
    currentStep.value = 0;
    router.push("/optimize/package");
  })

  
  return false;
}

/** 下一步操作 */
function handleNext() {
  let canProceed = false;
  
  if (currentStep.value == 0) {
    canProceed = handleStepOne();
  } else if (currentStep.value == 1) {
    canProceed = handleStepTwo();
  }else if (currentStep.value == 2) {
    canProceed = handleStepThree();
  }else if (currentStep.value == 3) {
    canProceed = handleStepFour();
  }

  if (canProceed) {
    currentStep.value += 1;
  }
}

/** 上一步操作 */
function handlePrevious() {
  currentStep.value -= 1;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getShelf(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改货架";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["shelfRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateShelf(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addShelf(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 状态改变 */
function handleStatusChange(row) {
  selectedShelvesIds.value = [];
  if (row.status == '1') {
    selectedShelvesIds.value.push(row.id);
  }
  for(let i = 0; i < shelfList.value.length; i++){
    const shelf = shelfList.value[i];
    if(shelf.id != row.id){
      shelf.status = '0';
    }
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const name = row.name || ids.value;
  proxy.$modal.confirm('是否确认删除货架名称为"' + name + '"的数据项？').then(function () {
    return delShelf(row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/**文件上传中处理 */
const handleShelfFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleShelfFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

function handleSortChange(column) {
  queryParams.value.orderByColumn = column.prop;
  if (column.order == 'ascending') {
    queryParams.value.isAsc = 'ASC';
  } else if (column.order == 'descending') {
    queryParams.value.isAsc = 'DESC';
  } else {
    queryParams.value.isAsc = null;
    queryParams.value.orderByColumn = null;
  }

  getList();
}




onActivated(() => {
  let packageId = orderStore.packageId 
  if(packageId != '' && packageId != null){
    currentStep.value = 2
    
    getReoptimizeParams(packageId).then(response => {
      console.log(response.data)
      selectedOrderIdList.value = response.data.orderIds
      selectedOrderThicknessList.value = [response.data.thickness]
      selectedOrderColorList.value = [response.data.color]
      requirementList.value = response.data.glassRequirements
      selectOriginalIds.value = response.data.originalIds
      selectedShelvesIds.value = [response.data.shelfId]
      getOriginalList()
      getOrderList(true)
      getList()

    });


    orderStore.setPackageId('');
    
  }else{
    getList();
  }
});


/** 订单相关 */

import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/order/order";
import { listRequirementByOrderIds } from "@/api/order/requirement";
import { ElMessage } from "element-plus";




const orderList = ref([]);
const orderLoading = ref(true);
const showOrderSearch = ref(true);
const orderTotal = ref(0);
const requirementTotal = ref(0);
const orderFileList = ref([]);
const selectedOrderIdList = ref([]);
const selectedOrderThicknessList = ref([]);
const selectedOrderColorList = ref([]);
const requirementList = ref([]);
const hasChange = ref(false);
const showMinWasteAlert = ref(false);


const orderData = reactive({
  orderForm: {},
  queryOrderParams: {
    pageNum: 1,
    pageSize: 50,
    name: null,
    beginThickness: null,
    endThickness: null,
    status: 0,
  },
  orderRules: {
  }
});

const requirementData = reactive({
  requirementForm: {},
  queryRequirementParams: {
    pageNum: 1,
    pageSize: 50,
    shelfId: null,
    shelfNum: null,
    shelfIndex: null,
    orderIds: null,
  },
  requirementRules: {
  }
});

/*** 订单导入参数 */
const orderUpload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题（批量导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  thickness: '',
  color: '',
  url: import.meta.env.VITE_APP_BASE_API + "/order/order/importData"
});

const { queryOrderParams, orderForm, orderRules } = toRefs(orderData);
const { queryRequirementParams, requirementForm, requirementRules } = toRefs(requirementData);

const rowClassNames = ref([
  'primary9', 'warning9', 'success9', 'info9', 'danger8', 'primary8', 'warning8', 'success8', 'info8','danger9', 
  'primary7', 'warning7', 'success7', 'info7', 'danger5', 'primary5', 'warning5', 'success5', 'info5','danger7', 
  'primary3', 'warning3', 'success3', 'info3', 'danger2', 'primary2', 'warning2', 'success2', 'info2','danger3', 
]);

const rowClassMap = ref({});

/** 查询订单选择列表 */
function getOrderList(notQueryRequirement) {
  orderLoading.value = true;
  listOrder(queryOrderParams.value).then(response => {
    orderList.value = response.rows;
    orderTotal.value = response.total;
    selectedOrderIdList.value = selectedOrderIdList.value.filter(id => orderList.value.some(order => order.id === id));
    selectedOrderThicknessList.value = selectedOrderThicknessList.value.filter(thickness => selectedOrderIdList.value.some(id => orderList.value.find(order => order.id === id && order.thickness === thickness)));
    selectedOrderColorList.value = selectedOrderColorList.value.filter(color => selectedOrderIdList.value.some(id => orderList.value.find(order => order.id === id && order.color === color)));
    orderLoading.value = false;
    if (selectedOrderIdList.value.length > 0) {
      selectedOrderIdList.value.forEach((orderId, index) => {
        if (index < rowClassNames.value.length) {
          rowClassMap.value[orderId] = rowClassNames.value[index];
        }
      });
    }
    if(notQueryRequirement == true){
      
    }else{
      getRequirementList();
    }
    
  });
}


// 表单重置
function orderReset() {
  orderForm.value = {
    id: null,
    createTime: null,
    createrId: null,
    name: null,
    piecesNumber: null,
    boxesNumber: null,
    thickness: null,
    minArea: null,
    maxArea: null,
    status: 0,
    operationId: null,
    beginThickness: null,
    endThickness: null
  };
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleOrderQuery() {
  queryOrderParams.value.pageNum = 1;
  getOrderList(false);
}

/** 重置按钮操作 */
function resetOrderQuery() {
  proxy.resetForm("queryOrderRef");
  handleOrderQuery();
}





/** 选择按钮操作 */
function handleOrderUpdate(row) {
  if (row.id != null) {
    if (selectedOrderIdList.value.indexOf(row.id) === -1) {
      // 选中时分配样式
      selectedOrderIdList.value.push(row.id);
      const usedClasses = Object.values(rowClassMap.value);
      const availableClass = rowClassNames.value.find(className =>
        !usedClasses.includes(className)
      );
      
      if (availableClass) {
        rowClassMap.value[row.id] = availableClass;
      }
      selectedOrderThicknessList.value.push(row.thickness);
      selectedOrderColorList.value.push(row.color);
    } else {
      // 取消选中时移除样式
      selectedOrderIdList.value.splice(selectedOrderIdList.value.indexOf(row.id), 1);
      delete rowClassMap.value[row.id];
      selectedOrderThicknessList.value.splice(selectedOrderThicknessList.value.indexOf(row.thickness), 1);
      selectedOrderColorList.value.splice(selectedOrderColorList.value.indexOf(row.color), 1);
    }
  }
  getRequirementList();
}



/** 删除按钮操作 */
function handleOrderDelete(row) {
  proxy.$modal.confirm('是否确认删除订单名称为"' + row.name + '"的数据项？').then(function () {
    return delOrder(row.id);
  }).then(() => {
    getOrderList(false);
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}



/**选择列的颜色 */
function tableRowClassName({ row }) {
  const name = rowClassMap.value[row.id] || ''
  return name;
}

function requirementRowClassName({ row }) {
  if (row.errorHighlight) {
    return 'error-row';
  }
  return rowClassMap.value[row.orderId] || '';
}


function handleOrderImport() {
  getSettingThicknessColor()
  orderUpload.title = "订单导入";
  orderUpload.open = true;
}

/**给右侧列表添加货架，如果有分架信息则增加，否则直接返回 */
function addShelfToRequirementList() {


  if(selectedShelvesIds.value.length == 0){
    return;
  }

  let maxOrderMap = new Map();
  for (let i = 0; i < requirementList.value.length; i++) {
    const requirement = requirementList.value[i];
    if(maxOrderMap.has(requirement.shelfNum)){
      maxOrderMap.set(requirement.shelfNum, Math.max(maxOrderMap.get(requirement.shelfNum), requirement.shelfOrder));
    }else{
      maxOrderMap.set(requirement.shelfNum, requirement.shelfOrder);
    }
  }

  
  for(let i = 0; i < requirementList.value.length; i++){
    const requirement = requirementList.value[i];
    requirement.shelfId = selectedShelvesIds.value[0];
    if(requirement.shelfNum == null || requirement.shelfNum == undefined){
      continue;
    }else if(requirement.shelfOrder == null || requirement.shelfOrder == undefined){
      let order = maxOrderMap.get(requirement.shelfNum);
      if(order == null || order == undefined){
        order = 0
      }
      requirement.shelfOrder = order;
      maxOrderMap.set(requirement.shelfNum,order + 1)
    }

  }
}
    


/** 获取右侧列表 */
function getRequirementList() {
  orderLoading.value = true;
  if (selectedOrderIdList.value.length > 0) {
    queryRequirementParams.value.orderIds = selectedOrderIdList.value;
    listRequirementByOrderIds(queryRequirementParams.value).then(response => {
      requirementList.value = response.rows;
      orderLoading.value = false;
      requirementTotal.value = response.total;
      addShelfToRequirementList()
    });
  } else {
    requirementList.value = [];
    requirementTotal.value = 0;
    orderLoading.value = false;
  }
}

/** 下载模板操作 */
function importOrderTemplate() {
  proxy.download("order/order/importTemplate", {
  }, `order_template_${new Date().getTime()}.xlsx`);
};


function handleOrderExceed(files, fileList) {

  ElMessage.error(`最多只能选择一个文件`);
}

/**文件上传中处理 */
const handleOrderFileUploadProgress = (event, file, fileList) => {
  orderUpload.isUploading = true;
};

/** 检查箱能否放入这个货架 */
function checkBoxCanShelf(box, shelf) {
  let area = shelf.crrrentArea;
  let thickness = shelf.currentThickness;
  let piecesNumber = shelf.currentPiecesNumber;
  let totalWeight = shelf.currentTotalWeight;
  let diffSpec = [];
  for (let i = 0; i < shelf.currentDiffSpec.length; i++) {
    diffSpec.push(shelf.currentDiffSpec[i]);
  }
  let longSideMin = shelf.currentLongSideMin;
  let longSideMax = shelf.currentLongSideMax;
  let shortSideMin = shelf.currentShortSideMin;
  let shortSideMax = shelf.currentShortSideMax;

  for (let i = 0; i < box.requirements.length; i++) {
    const requirement = box.requirements[i];
    area += requirement.width * requirement.length * requirement.piecesNumber;
    if (area > shelf.maxArea) {
      return false;
    }
    thickness += box.thickness * requirement.piecesNumber;
    if (thickness > shelf.maxThickness) {
      return false;
    }
    piecesNumber += requirement.piecesNumber;
    if (piecesNumber > shelf.maxPiecesNumber) {
      return false;
    }
    totalWeight = box.thickness * area * 2.5;
    if (totalWeight > shelf.maxTotalWeight) {
      return false;
    }
    let hasSame = false;
    for (let j = 0; j < diffSpec.length; j++) {
      const diffSpecItem = diffSpec[j];
      if ((diffSpecItem.width == requirement.width && diffSpecItem.length == requirement.length) ||
        (diffSpecItem.width == requirement.length && diffSpecItem.length == requirement.width)) {
        hasSame = true;
        break;
      }
    }
    if (!hasSame) {
      diffSpec.push(requirement);
    }
    if (diffSpec.length > shelf.maxDiffSpec) {
      return false;
    }
    let longSide = requirement.width > requirement.length ? requirement.width : requirement.length;
    let shortSide = requirement.width < requirement.length ? requirement.width : requirement.length;
    if (longSide < longSideMin) {
      longSideMin = longSide;
    }
    if (shortSide > shortSideMax) {
      shortSideMax = shortSide;
    }
    if (longSide > longSideMax) {
      longSideMax = longSide;
    }
    if (shortSide < shortSideMin) {
      shortSideMin = shortSide;
    }
    if (longSideMax - longSideMin > shelf.maxLongSideDiff) {
      return false;
    }
    if (shortSideMax - shortSideMin > shelf.maxShortSideDiff) {
      return false;
    }
  }
  return true;
}

//将箱放入货架中
function putBoxToShelf(box, shelf) {
  shelf.boxList.push(box);
  for (let i = 0; i < box.requirements.length; i++) {
    const requirement = box.requirements[i];
    shelf.currentArea += requirement.width * requirement.length * requirement.piecesNumber;
    
    shelf.currentThickness += box.thickness * requirement.piecesNumber;
    shelf.currentPiecesNumber += requirement.piecesNumber;
    shelf.currentTotalWeight = box.thickness * shelf.currentArea * 2.5;
    requirement.shelfNum = shelf.shelfNum;
    requirement.shelfOrder = shelf.shelfOrder;
    requirement.shelfId = shelf.id;
    shelf.shelfOrder++;
    let longSide = requirement.width > requirement.length ? requirement.width : requirement.length;
    let shortSide = requirement.width < requirement.length ? requirement.width : requirement.length;
    shelf.currentLongSideMin = Math.min(shelf.currentLongSideMin, longSide);
    shelf.currentLongSideMax = Math.max(shelf.currentLongSideMax, longSide);
    shelf.currentShortSideMin = Math.min(shelf.currentShortSideMin, shortSide);
    shelf.currentShortSideMax = Math.max(shelf.currentShortSideMax, shortSide);

  
    for (let j = 0; j < shelf.currentDiffSpec.length; j++) {
      const diffSpecItem = shelf.currentDiffSpec[j];
      if (!(diffSpecItem.width == requirement.width && diffSpecItem.length == requirement.length) &&
        !(diffSpecItem.width == requirement.length && diffSpecItem.length == requirement.width)) {
          let tmpDiffSpecItem = {};
          tmpDiffSpecItem.width = requirement.width;
          tmpDiffSpecItem.length = requirement.length;
          shelf.currentDiffSpec.push(tmpDiffSpecItem);
      }
    }
  }
}

//将箱从货架中移除
function removeLastBoxFromShelf(shelf) {
  if (shelf.boxList.length == 0) {
    return;
  }
  const box = shelf.boxList[shelf.boxList.length - 1];
  shelf.boxList.splice(shelf.boxList.length - 1, 1);

  for (let i = 0; i < box.requirements.length; i++) {
    const requirement = box.requirements[i];
    requirement.shelfNum = null;
    requirement.shelfOrder = null;
    requirement.shelfId = null;
    shelf.currentPiecesNumber -= requirement.piecesNumber;
    shelf.currentArea -= requirement.width * requirement.length * requirement.piecesNumber;
    shelf.currentThickness -= box.thickness * requirement.piecesNumber;
    shelf.currentTotalWeight = box.thickness * shelf.currentArea * 2.5 * 1e-6;
  }

  let tmpDiffSpec = [];
  for (let i = 0; i < shelf.boxList.length; i++) {
    const box = shelf.boxList[i];
    for (let j = 0; j < box.requirements.length; j++) {
      const requirement = box.requirements[j];
      let hasSame = false;
      for (let k = 0; k < shelf.currentDiffSpec.length; k++) {
        const diffSpecItem = shelf.currentDiffSpec[k];
        if ((diffSpecItem.width == requirement.width && diffSpecItem.length == requirement.length) ||
          (diffSpecItem.width == requirement.length && diffSpecItem.length == requirement.width)) {
          hasSame = true;
          break;
        }
      }
      if (!hasSame) {
        tmpDiffSpec.push(requirement);
      }
    }
  }
  shelf.currentDiffSpec = tmpDiffSpec;
  shelf.currentLongSideMax = 0;
  shelf.currentShortSideMax = 0;
  shelf.currentLongSideMin = 10000000;
  shelf.currentShortSideMin = 10000000;
  for (let i = 0; i < shelf.currentDiffSpec.length; i++) {
    const diffSpecItem = shelf.currentDiffSpec[i];
    const longSide = diffSpecItem.width > diffSpecItem.length ? diffSpecItem.width : diffSpecItem.length;
    const shortSide = diffSpecItem.width < diffSpecItem.length ? diffSpecItem.width : diffSpecItem.length;
    if (longSide > shelf.currentLongSideMax) {
      shelf.currentLongSideMax = longSide;
    }
    if (shortSide > shelf.currentShortSideMax) {
      shelf.currentShortSideMax = shortSide;
    }
    if (longSide < shelf.currentLongSideMin) {
      shelf.currentLongSideMin = longSide;
    }
    if (shortSide < shelf.currentShortSideMin) {
      shelf.currentShortSideMin = shortSide;
    }
  }
}

//根据选中的货架进行初始化
function initShelf(shelf) {
  let tmpshelf = {};
  
  tmpshelf.maxArea = shelf.maxArea;

  tmpshelf.thickness = shelf.thickness;

  tmpshelf.maxPiecesNumber = shelf.maxPiecesNumber;
  tmpshelf.maxTotalWeight = shelf.maxTotalWeight;
  tmpshelf.maxLongSideDiff = shelf.maxLongSideDiff;
  tmpshelf.maxShortSideDiff = shelf.maxShortSideDiff;
  tmpshelf.maxDiffSpec = shelf.maxDiffSpec;
  tmpshelf.id = shelf.id;
  tmpshelf.currentArea = 1.0;
  tmpshelf.currentThickness = 0.0;
  tmpshelf.currentPiecesNumber = 0;
  tmpshelf.currentTotalWeight = 0.0;
  tmpshelf.currentDiffSpec = [];
  tmpshelf.currentLongSideMin = 10000000.0;
  tmpshelf.currentLongSideMax = 0.0;
  tmpshelf.currentShortSideMin = 10000000.0;
  tmpshelf.currentShortSideMax = 0.0;
  tmpshelf.boxList = [];
  tmpshelf.shelfOrder = 0;
  tmpshelf.name = shelf.name;


  return tmpshelf;
}

function oneBoxShelf() {
  if (selectedOrderIdList.value.length == 0) {
    proxy.$modal.msgError("请选择至少一个订单");
    return;
  }

  if (requirementList.value.length == 0) {
    proxy.$modal.msgError("当前订单无需分配货架");
    return;
  }

  const uniqueThicknessList = [...new Set(selectedOrderThicknessList.value)];
  if (uniqueThicknessList.length > 1) {
    proxy.$modal.msgError("只能选择一种厚度的订单");
    return;
  }

  const uniqueColorList = [...new Set(selectedOrderColorList.value)];
  if (uniqueColorList.length > 1) {
    proxy.$modal.msgError("只能选择一种颜色的订单");
    return;
  }


  const selectedShelfList = shelfList.value.filter(shelf => selectedShelvesIds.value.some(id => id === shelf.id));
  if (selectedShelfList.length == 0) {
    proxy.$modal.msgError("请选择至少一个货架");
    return;
  }

  let boxIndexMap = new Map();
  let boxNumMap = new Map();
  let boxNum = 0;

  for(let i = 0; i < requirementList.value.length; i++){
    const requirement = requirementList.value[i];
    if(boxIndexMap.has(requirement.boxName)){
      boxIndexMap.set(requirement.boxName, boxIndexMap.get(requirement.boxName) + 1);
    } else {
      boxIndexMap.set(requirement.boxName, 0);
      boxNumMap.set(requirement.boxName, boxNum);
      boxNum ++;
    }
    if(boxNum < selectedShelfList[0].leftNumber){
      requirement.shelfId = selectedShelfList[0].id;
      requirement.shelfOrder = boxIndexMap.get(requirement.boxName);
      requirement.shelfNum = boxNumMap.get(requirement.boxName);
    }else{
      proxy.$modal.msgError("货架数量不足，箱号：" + requirement.boxName);
      return;
    }
  }
}

// 自动分配货架
const handleOrderAutoShelf = () => {
  if (selectedOrderIdList.value.length == 0) {
    proxy.$modal.msgError("请选择至少一个订单");
    return;
  }

  if (requirementList.value.length == 0) {
    proxy.$modal.msgError("当前订单无需分配货架");
    return;
  }

  const uniqueThicknessList = [...new Set(selectedOrderThicknessList.value)];
  if (uniqueThicknessList.length > 1) {
    proxy.$modal.msgError("只能选择一种厚度的订单");
    return;
  }

  const uniqueColorList = [...new Set(selectedOrderColorList.value)];
  if (uniqueColorList.length > 1) {
    proxy.$modal.msgError("只能选择一种颜色的订单");
    return;
  }


  const selectedShelfList = shelfList.value.filter(shelf => selectedShelvesIds.value.some(id => id === shelf.id));
  if (selectedShelfList.length == 0) {
    proxy.$modal.msgError("请选择至少一个货架");
    return;
  }

  // 根据 priority 对 shelfList 进行排序（降序）
  const sortedShelfList = [...selectedShelfList].sort((a, b) => {
    return b.priority - a.priority;
  });

  let tmpOrderList = [];

  for (let i = 0; i < requirementList.value.length; i++) {
    const requirement = requirementList.value[i];
    
    // 检查tmpOrderList中是否已存在该requirement的id
    const existingOrderIndex = tmpOrderList.findIndex(order => order.id === requirement.orderId);

    if (existingOrderIndex === -1) {
      // 如果不存在，则添加到临时订单列表中
      tmpOrderList.push({
        id: requirement.orderId,
        boxes: [{
          name: requirement.boxName,
          requirements: [requirement],
          orderId: requirement.orderId,
          thickness: uniqueThicknessList[0],
        }],
      });
    } else {
      let tmpBox = tmpOrderList[existingOrderIndex].boxes.find(box => box.name === requirement.boxName);
      if (tmpBox) {
        tmpBox.requirements.push(requirement);
      } else {
        tmpOrderList[existingOrderIndex].boxes.push({
          name: requirement.boxName,
          requirements: [requirement],
          orderId: requirement.orderId,
          thickness: uniqueThicknessList[0],
        });
      }
    }
  }
  
  let tmpShelfList = [];
  let beginShelfIndex = 0;
  let shelfUsed = 0;

  for (let i = 0; i < tmpOrderList.length; i++) {
    const tmpOrder = tmpOrderList[i];
    for (let j = 0; j < tmpOrder.boxes.length; j++) {
      const tmpBox = tmpOrder.boxes[j];
      let boxCanShelf = false;
      let tmpshelf = {}
      //从beginShelfIndex开始，检查货架是否能满足需求
      for (let k = beginShelfIndex; k < tmpShelfList.length; k++) {
        if (checkBoxCanShelf(tmpBox, tmpShelfList[k])) {
          boxCanShelf = true;
          tmpshelf = tmpShelfList[k];
          break;
        }
      }
      //如果不能满足需求，则需要重新分配货架
      if (!boxCanShelf) {
        
        for (let k = 0; k < selectedShelfList.length; k++) {
          if (selectedShelfList[k].leftNumber > 0) {
            tmpshelf = initShelf(selectedShelfList[k]);
            
          }
          if (checkBoxCanShelf(tmpBox, tmpshelf)) {
            selectedShelfList[k].leftNumber--;
            tmpshelf.shelfNum = tmpShelfList.length;
            tmpShelfList.push(tmpshelf);
            boxCanShelf = true;
            shelfUsed++;
            break;
          }
        }
        //如果没有可以分配的货架，则报错；
        if (!boxCanShelf) {
          proxy.$modal.msgError("货架无法满足需求，箱号：" + tmpBox.name);
          return;
        } else {
          putBoxToShelf(tmpBox, tmpshelf);
        }
      } else {
        putBoxToShelf(tmpBox, tmpshelf);
      }
    }
    beginShelfIndex += shelfUsed;
    shelfUsed = 0;
  }


  for (let i = 0; i < tmpShelfList.length; i++) {
    const shelf = tmpShelfList[i];
    if (shelf.name === 'A型架') {
      if (shelf.boxList.length > 2 && shelf.boxList.length % 2 == 1) {

        let box = shelf.boxList[shelf.boxList.length - 1];
        let solved = false;
        removeLastBoxFromShelf(shelf);
        const orderId = box.orderId;
        //从i+1开始，检查后续货架是否能满足需求
        for (let j = i + 1; j < tmpShelfList.length; j++) {
          const nextShelf = tmpShelfList[j];
          //如果后续货架为空，则将箱放入后续货架
          if (nextShelf.boxList.length == 0 && checkBoxCanShelf(box, nextShelf)) {
            putBoxToShelf(box, nextShelf);
            solved = true;
            break;
          } else if (orderId == nextShelf.boxList[0].orderId) { //同一个订单才能放在一个货架
            if (nextShelf.name != 'A型架' && checkBoxCanShelf(box, nextShelf)) {//不是A型架，不考虑奇偶性，能够放入就放入
              putBoxToShelf(box, nextShelf);
              solved = true;
              break;
            } else if (nextShelf.boxList.length % 2 != 0 && checkBoxCanShelf(box, nextShelf)) {//是A型架，可以凑成偶数，且够放入才放入
              putBoxToShelf(box, nextShelf);
              solved = true;
              break;
            }
          }
        }
        if (!solved) {
          //使用新的货架
          let tmpshelf = {};
          for (let k = 0; k < selectedShelfList.length; k++) {
            if (selectedShelfList[k].leftNumber > 0) {
              tmpshelf = initShelf(selectedShelfList[k]);
              if (checkBoxCanShelf(box, tmpshelf)) {
                selectedShelfList[k].leftNumber--;
                tmpshelf.shelfNum = tmpShelfList.length;
                tmpShelfList.push(tmpshelf);
                putBoxToShelf(box, tmpshelf);
                
                solved = true;
                break;
              }
            }
          }
          if (!solved) {//如果还是没有找到合适的货架，则报错
            proxy.$modal.msgError("货架无法满足需求，箱号：" + box.name);
            return;
          }
        }
      }
    }
  }
}


/** 文件上传成功处理 */
const handleOrderFileSuccess = (response, file, fileList) => {
  orderUpload.open = false;
  orderUpload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getOrderList(false);
};

/** 文件上传改变处理 */
const handleOrderChange = (file, fileList1) => {
  orderFileList.value = fileList1;
}



/** 提交上传文件 */
function submitOrderFileForm(event) {
  if (orderUpload.thickness == null || orderUpload.thickness == '') {
    proxy.$modal.msgError("请输入厚度");
    return;
  }
  if (orderUpload.color == null || orderUpload.color == '') {
    proxy.$modal.msgError("请输入颜色");
    return;
  }

  proxy.$refs["uploadRef"].submit()
};

function handleOrderSortChange(column) {
  queryOrderParams.value.orderByColumn = column.prop;
  if (column.order == 'ascending') {
    queryOrderParams.value.isAsc = 'ASC';
  } else if (column.order == 'descending') {
    queryOrderParams.value.isAsc = 'DESC';
  } else {
    queryOrderParams.value.isAsc = null;
    queryOrderParams.value.orderByColumn = null;
  }
  getOrderList(false);
}

function handleRequirementQuery() {
  queryRequirementParams.value.pageNum = 1;
  getRequirementList();

}

function resetRequirementQuery() {
  proxy.resetForm("queryRequirementRef");
  handleRequirementQuery();
}

function handleMinWasteChange() {
  if (paramConfig.value.minWaste < 10) {
    showMinWasteAlert.value = true;
  }else{
    showMinWasteAlert.value = false;
  }
  hasChange.value = true;
}



function handleShelfNumberInput(currentIndex) {
  const currentValue = requirementList.value[currentIndex];
  console.log(currentValue);
  hasChange.value = true;
}

function handleShelfIndexInput(currentIndex) {
  const currentValue = requirementList.value[currentIndex];
  hasChange.value = true;
}

function handleShelfTypeChange(currentIndex) {
  const currentValue = requirementList.value[currentIndex];
  hasChange.value = true;
}

// 原片
import { listOriginal, getOriginal, delOriginal, addOriginal, updateOriginal } from "@/api/order/original";

const showOriginalSearch = ref(true);
const originalList = ref([]);
const originalLoading = ref(true);
const originalTitle = ref("");
const originalOpen = ref(false);
const originalTotal = ref(0);
const originalSingle = ref(true);
const originalMultiple = ref(true);
const originalIds = ref([]);
const selectOriginalAll = ref(false);
const selectOriginalIds = ref([])



/*** 原片导入参数 */
const originalUpload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题（批量导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  color: null,
  thickness: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },

  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/order/original/importData"
});

const originalData = reactive({
  originalForm: {},
  queryOriginalParams: {
    pageNum: 1,
    pageSize: 50,
    createrId: null,
    batch: null,
    type: null,
    thickness: null,
    width: null,
    length: null,
    availableNumber: null,
    color: null,
    price: null,
    updateTime: null,
    totalUsed: null,
    monthUsed: null,
    beginThickness: null,
    endThickness: null,
    beginWidth: null,
    endWidth: null,
    beginLength: null,
    endLength: null,
    beginPrice: null,
    endPrice: null,
    beginAvailableNumber: null,
    endAvailableNumber: null,
    isSurplus: 0,
  },
  originalRules: {
    type: [
      { required: true, message: "类型不能为空", trigger: "blur" }
    ],
    availableNumber: [
      { required: true, message: "数量不能为空", trigger: "blur" }
    ],
    width: [
      { required: true, message: "宽度不能为空", trigger: "blur" }
    ],
    length: [
      { required: true, message: "高度不能为空", trigger: "blur" }
    ],
    
  }
});

const { queryOriginalParams, originalForm, originalRules } = toRefs(originalData);


// 多选框选中数据
function handleOriginalSelectionChange(selection) {
  originalIds.value = selection.map(item => item.id);
  originalSingle.value = selection.length != 1;
  originalMultiple.value = !selection.length;
}

// 更新排序方式
function handleOriginalSortChange(column) {
  queryOriginalParams.value.orderByColumn = column.prop;
  if(column.order == 'ascending') {
    queryOriginalParams.value.isAsc = 'ASC';
  } else if(column.order == 'descending') {
    queryOriginalParams.value.isAsc = 'DESC';
  } else {
    queryOriginalParams.value.isAsc = null;
    queryOriginalParams.value.orderByColumn = null;
  }
  getList();
}

function getRandomColor(){
  const colors = [
    '#FFB6C1', // 浅粉色
    '#87CEEB', // 天蓝色
    '#98FB98', // 浅绿色
    '#DDA0DD', // 梅红色
    '#F0E68C', // 卡其色
    '#E6E6FA', // 淡紫色
    '#FFA07A', // 浅橙色
    '#B0E0E6', // 粉蓝色
    '#FFE4B5', // 浅黄色
    '#D8BFD8'  // 蓟色
  ];
  return colors[Math.floor(Math.random() * colors.length)];
}


/** 搜索按钮操作 */
function handleOriginalQuery() {
  queryOriginalParams.value.pageNum = 1;
  getOriginalList();
}

/** 重置按钮操作 */
function resetOriginalQuery() {
  proxy.resetForm("queryOriginalRef");
  handleOriginalQuery();
}

/** 下载原片模板操作 */
function importOriginalTemplate() {
  proxy.download("order/original/importTemplate", {
  }, `original_template_${new Date().getTime()}.xlsx`);
};

/** 查询原片列表 */
function getOriginalList() {
  //originalLoading.value = true;
  queryOriginalParams.value.thickness = selectedOrderThicknessList.value[0] || null;
  queryOriginalParams.value.color = selectedOrderColorList.value[0] || null;
  listOriginal(queryOriginalParams.value).then(response => {
    originalList.value = response.rows;
    originalList.value.forEach(item => {
      if (selectOriginalIds.value.includes(item.id)) {
        item.status = '1';
      }  else {
        item.status = '0';
      }
      item.priority = 1;
    });
    originalTotal.value = response.total;
    originalLoading.value = false;
  });
  originalLoading.value = false;
}


function handleBoxOrderChange(status){
  if(status == 1){
    paramConfig.value.maxShelf = paramConfig.value.maxShelfUser
  }else{
    paramConfig.value.maxShelfUser = paramConfig.value.maxShelf
    paramConfig.value.maxShelf = 999;
  }
}

/** 批量导入操作 */
function handleOriginalImport() {
  originalUpload.title = "原片导入";
  originalUpload.open = true;
}

/** 新增原片 */
function handleOriginalAdd() {
  originalOpen.value = true;
  originalTitle.value = "新增原片";
}

/** 全选改变 */
function selectOriginalAllChange(selection) {
  if(selection) {
    for(let i = 0; i < originalList.value.length; i++) {
      if (originalList.value[i].status === undefined || originalList.value[i].status === "0") {
        originalList.value[i].status = "1"
      } 
    }
    selectOriginalIds.value = originalList.value.map(item => item.id);
  } else {
    for(let i = 0; i < originalList.value.length; i++) {
      originalList.value[i].status = "0"
    }
    selectOriginalIds.value = [];
  }
}

/** 提交上传文件 */
function submitOriginalFileForm() {
  originalUpload.color = selectedOrderColorList.value[0];
  originalUpload.thickness = selectedOrderThicknessList.value[0];
  console.log(originalUpload);
  proxy.$refs["originalUploadRef"].submit();
};



/** 文件上传成功处理 */
const handleOriginalFileSuccess = (response, file, fileList) => {
  originalUpload.open = false;
  originalUpload.isUploading = false;
  proxy.$refs["originalUploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getOriginalList();
};

/**文件上传中处理 */
const handleOriginalFileUploadProgress = (event, file, fileList) => {
  originalUpload.isUploading = true;
};

function handleOriginalSelectChanged(row) {
  const selection = row.status

  if(selection == "0"){
    selectOriginalAll.value = false
    selectOriginalIds.value = selectOriginalIds.value.filter(id => id != row.id);
  }else {
    selectOriginalIds.value.push(row.id);
    let check = true
    for(let i = 0; i < originalList.value.length; i++) {
      if( typeof originalList.value[i].status === 'undefined') {
        check = false
        break
      } else if(originalList.value[i].status === "0"){
        check = false
        break
      }
    }
    selectOriginalAll.value = check
  }
}

function handleOriginalDelete(row) {

  proxy.$modal.confirm('确认删除原片？').then(function () {
    return delOriginal(row.id);
  }).then(() => {
    getOriginalList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/**修改原片 */
function handleOriginalUpdate(row) {
  updateOriginal(row).then(response => {
    getOriginalList();
  });
}

function resetOriginalForm() {
  originalForm.value = {
    name: null,
    thickness: null,
    color: null,
    availableNumber: null,
    price: null,
    updateTime: null,
    totalUsed: null,
    monthUsed: null,
    beginThickness: null,
    endThickness: null,
    beginWidth: null,
    endWidth: null,
    beginLength: null,
    endLength: null,
    beginPrice: null,
    endPrice: null,
    beginAvailableNumber: null,
    endAvailableNumber: null,
  };
}


// 取消按钮
function originalCancel() {
  originalOpen.value = false;
  resetOriginalForm();
}

function handleOriginalSubmit() {
  proxy.$refs["originalRef"].validate(valid => {
    if (valid) {
      if (originalForm.value.id != null) {
        updateOriginal(originalForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          originalOpen.value = false;
          getOriginalList();  
        });
      } else {
        originalForm.value.color = selectedOrderColorList.value[0];
        originalForm.value.thickness = selectedOrderThicknessList.value[0];
        addOriginal(originalForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          originalOpen.value = false;
          getOriginalList();
        });
      }
    }
  });
}

/** 优化参数设置 */
const containedLoading = ref(true);
const containedOrderList = ref([]);
const containedOrderTotal = ref(0);
const containedOriginalList = ref([]);
const containedOriginalTotal = ref(0);
const settingThicknessList = ref([])
const settingColorList = ref([])

import { listProcess,getThicknessColor } from "@/api/setting/process";
import { listOrderByIds } from "@/api/order/order";
import { listOriginalByIds } from "@/api/order/original";
import { addPackage, updatePackage,getReoptimizeParams } from "@/api/optimize/package";

const paramData = reactive({
  paramConfig: {
    grind:1.0, // 磨边量
    cuttingSpeed: 10, // 切割速度
    minWaste: 10, // 最小余料
    max1Cut: 6000, // 最大刀距-X 一般来说固定
    min1Cut: 10, // 最小刀距-X  一般来说固定
    min2Cut: 10, // 最小刀距-Y  一般来说固定
    min13Cut: 10, // 最小刀距-XZ 一般来说等于掰边距
    maxShelf: 4, // 成品开架数
    maxShelfUser:4,//在关闭时记录用户输入
    trimBottom: 0, // 原片修边量-下
    trimTop: 0, // 原片修边量-上
    trimLeft: 0, // 原片修边量-左
    trimRight: 0, // 原片修边量-右
    cutReverse: 0, // 输出反切
    optimizeScrap: false, // 优化余料
    criticalOffsetDistance: 0, // 临界错落距离
    treeDepth: 6, // 切割树深度
    originalShelvesNumber: 0,//原片开架数
    originalShelvesNumberUser:0,
    throughCut: true, // 通刀约束
    name: null, // 名称
    isOffline: 1, // 是否离线
    thickness: null, // 厚度
    color: null, // 颜色
    glassRequirements: [],
    glassOriginals: [],
    type: 1,
    tailLength: null,
    tailWidth: null
  },
  paramRules: {
  name: [
    { required: true, message: "名称不能为空", trigger: "blur" }
    ],
  }
})

import useOrderStore  from '@/store/modules/order'
const orderStore = useOrderStore()

const processData = reactive({
  processForm: {},
  processQueryParams: {
    pageNum: 1,
    pageSize: 50,
    originalType: null,
    thickness: null,
    minWaste: null,
    max1Cut: null,
    min1Cut: null,
    min2Cut: null,
    min13Cut: null,
    trimLeft: null,
    trimRight: null,
    trimTop: null,
    trimBottom: null
  },
  processRules: {
    createTime: [
      { required: true, message: "原片类型不能为空", trigger: "blur" }
    ],
  }
});

const containedOrderData = reactive({
  containedOrderForm: {},
  containedOrderQueryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    piecesNumber: null,
    boxesNumber: null,
    thickness: null,
    minArea: null,
    maxArea: null,
  },
  containedOrderRules: {
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
  }
});

const containedOriginalData = reactive({
  containedOriginalForm: {},
  containedOriginalQueryParams: {
    pageNum: 1,
    pageSize: 10,
    ids: [],
  },
  containedOriginalRules: {
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
  }
});

const { paramConfig, paramRules } = toRefs(paramData);
const { processForm, processQueryParams, processRules } = toRefs(processData);
const { containedOrderForm, containedOrderQueryParams, containedOrderRules } = toRefs(containedOrderData);
const { containedOriginalForm, containedOriginalQueryParams, containedOriginalRules } = toRefs(containedOriginalData);

/** 查询工艺参数 */
function getProcessList() {
  processQueryParams.value.thickness = selectedOrderThicknessList.value[0]||null;
  processQueryParams.value.color = selectedOrderColorList.value[0]||null;
  paramConfig.value.tailLength = orderStore.tailLength || null;
  paramConfig.value.tailWidth = orderStore.tailWidth || null;
  listProcess(processQueryParams.value).then(response => {
    loadParamConfig(response);
  });
}

/** 加载工艺参数 */
function loadParamConfig(response) {
  paramConfig.value.minWaste = response.rows[0].minWaste;
  paramConfig.value.max1Cut = response.rows[0].max1Cut;
  paramConfig.value.min1Cut = response.rows[0].min1Cut;
  paramConfig.value.min2Cut = response.rows[0].min2Cut;
  //暂时与minwaste一致
  paramConfig.value.min13Cut = response.rows[0].min13Cut;
  paramConfig.value.trimLeft = response.rows[0].trimLeft;
  paramConfig.value.trimRight = response.rows[0].trimRight;
  paramConfig.value.trimTop = response.rows[0].trimTop;
  paramConfig.value.trimBottom = response.rows[0].trimBottom;
}

/** 查询订单选择列表 */
function getContainedOrderList() {
  containedLoading.value = true;
  containedOrderQueryParams.value.ids = selectedOrderIdList.value
  if(selectedOrderIdList.value.length == 0) {
    containedLoading.value = false;
    proxy.$modal.msgError("订单不能为空");
    return;
  }
  listOrderByIds(containedOrderQueryParams.value).then(response => {
    containedOrderList.value = response.rows;
    containedOrderTotal.value = response.total;
    containedLoading.value = false;
  });
}


function getSettingThicknessColor(){
  getThicknessColor().then(response=> {
    let thicknessList = []
    let colorList = []
    for (let index = 0; index < response.rows.length; index++) {
      const element = response.rows[index];
      thicknessList.push(element.thickness)
      colorList.push(element.color)
    }
    settingThicknessList.value = [...new Set(thicknessList)];
    settingColorList.value = [...new Set(colorList)];
  })
}

/** 查询原片列表 */
function getContainedOriginalList() {
  loading.value = true;
  const queryIds = selectOriginalIds 
  containedOriginalQueryParams.value.ids = queryIds
  if(queryIds.length == 0) {
    loading.value = false;
    proxy.$modal.msgError("原片不能为空");
    return;
  }
  listOriginalByIds(containedOriginalQueryParams.value).then(response => {
    containedOriginalList.value = response.rows;
    containedOriginalTotal.value = response.total;
    loading.value = false;
    for (let i = 0; i < containedOriginalList.value.length; i++) {
        for(let j = 0; j < originalList.value.length; j++) {
          if(containedOriginalList.value[i].id == originalList.value[j].id) {
            containedOriginalList.value[i].priority = originalList.value[j].priority;
          }
        }
        if(containedOriginalList.value[i].priority === null || containedOriginalList.value[i].priority === undefined) {
          containedOriginalList.value[i].priority = 1;
        }
    }
  });
}

</script>

<style scoped>
.right-align-col {
  margin-left: auto;
}

.navigation-btn {
  min-width: 90px;
  transition: all 0.3s;
  border-radius: 4px;
  font-weight: 500;
}

.prev-btn {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.prev-btn:hover:not(:disabled) {
  transform: translateX(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.next-btn {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.next-btn:hover {
  transform: translateX(2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

/* 表格样式 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

:deep(.el-table__header-wrapper) {
  background-color: #f5f7fa;
}

:deep(.el-table__header) {
  font-weight: 600;
}

:deep(.el-table__row) {
  transition: all 0.3s;
}

:deep(.el-table__row:hover) {
  background-color: #f0f9ff !important;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  padding: 12px 0;
}

:deep(.el-table--striped .el-table__row.striped) {
  background-color: #fafafa;
}

:deep(.el-table--enable-row-hover .el-table__row:hover) {
  background-color: #f0f9ff;
}

:deep(.el-table .error-row) {
  background-color: #fff0f0;
  animation: error-highlight 1.5s ease-in-out;
}

@keyframes error-highlight {
  0%, 100% { background-color: #fff0f0; }
  50% { background-color: #ffdddd; }
}

/* 分页样式 */
:deep(.el-pagination) {
  margin-top: 20px;
  padding: 10px;
  border-radius: 8px;
  background-color: #f5f7fa;
  display: flex;
  justify-content: center;
}

/* 表单样式 */
:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-input), :deep(.el-select) {
  border-radius: 4px;
}

:deep(.el-input__inner) {
  transition: all 0.3s;
}

:deep(.el-input__inner:focus) {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

:deep(.el-dialog__header) {
  padding: 15px 20px;
  background-color: #f5f7fa;
  margin-right: 0;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
}

/* 步骤条样式 */
:deep(.el-steps) {
  margin-bottom: 20px;
}

:deep(.el-step__title) {
  font-weight: 500;
}

:deep(.el-step__icon.is-text) {
  border-radius: 50%;
  border: 2px solid;
}

:deep(.el-step__line) {
  background-color: rgb(240, 11, 11);
  top: 50%;
  height: 1px;
}


/* 自定义头部样式 */
.custom-header {
  background-color: #f5f7fa;
  font-weight: 600;
  padding: 10px 15px;
  border-radius: 6px 6px 0 0;
  border: 1px solid #e4e7ed;
  border-bottom: none;
  color: #303133;
}

/* 居中列样式 */
.centered-col {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.centered-col:last-child {
  border-bottom: none;
}

/* 架选择容器 */
.shelf-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 表格内按钮样式 */
:deep(.el-button--text) {
  padding: 4px 8px;
  border-radius: 4px;
}

:deep(.el-button--text:hover) {
  background-color: rgba(64, 158, 255, 0.1);
}

/* 上传区域样式 */
:deep(.el-upload-dragger) {
  border-radius: 8px;
  transition: all 0.3s;
}

:deep(.el-upload-dragger:hover) {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.05);
}

/* 表格内的输入框样式 */
:deep(.el-table .el-input) {
  margin: 0 auto;
}

:deep(.el-table .el-input-number) {
  width: 100%;
}

/* 表格内的选择器样式 */
:deep(.el-table .el-select) {
  width: 100%;
}

:deep(.el-table .warning9) {
  --el-table-tr-bg-color: var(--el-color-warning-light-9) !important;
}
:deep(.el-table .warning8) {
  --el-table-tr-bg-color: var(--el-color-warning-light-8) !important;
}
:deep(.el-table .warning7) {
  --el-table-tr-bg-color: var(--el-color-warning-light-7) !important;
}
:deep(.el-table .warning5) {
  --el-table-tr-bg-color: var(--el-color-warning-light-5) !important;
}
:deep(.el-table .warning3) {
  --el-table-tr-bg-color: var(--el-color-warning-light-3) !important;
}
:deep(.el-table .warning2) {
  --el-table-tr-bg-color: var(--el-color-warning-dark-2) !important;
}
:deep(.el-table .success9) {
  --el-table-tr-bg-color: var(--el-color-success-light-9) !important;
}
:deep(.el-table .success8) {
  --el-table-tr-bg-color: var(--el-color-success-light-8) !important;
}
:deep(.el-table .success7) {
  --el-table-tr-bg-color: var(--el-color-warning-light-7) !important;
}
:deep(.el-table .success5) {
  --el-table-tr-bg-color: var(--el-color-success-light-5) !important;
}
:deep(.el-table .success3) {
  --el-table-tr-bg-color: var(--el-color-success-light-3) !important;
}
:deep(.el-table .success2) {
  --el-table-tr-bg-color: var(--el-color-success-dark-2) !important;
}

:deep(.el-table .primary9) {
  --el-table-tr-bg-color: var(--el-color-primary-light-9) !important;
}
:deep(.el-table .primary8) {
  --el-table-tr-bg-color: var(--el-color-primary-light-8) !important;
}
:deep(.el-table .primary7) {
  --el-table-tr-bg-color: var(--el-color-primary-light-7) !important;
}
:deep(.el-table .primary5) {
  --el-table-tr-bg-color: var(--el-color-primary-light-5) !important;
}
:deep(.el-table .primary3) {
  --el-table-tr-bg-color: var(--el-color-primary-light-3) !important;
}
:deep(.el-table .primary2) {
  --el-table-tr-bg-color: var(--el-color-primary-dark-2) !important;
}

:deep(.el-table .danger9) {
  --el-table-tr-bg-color: var(--el-color-danger-light-9) !important;
}
:deep(.el-table .danger8) {
  --el-table-tr-bg-color: var(--el-color-danger-light-8) !important;
}
:deep(.el-table .danger7) {
  --el-table-tr-bg-color: var(--el-color-danger-light-7) !important;
}
:deep(.el-table .danger5) {
  --el-table-tr-bg-color: var(--el-color-danger-light-5) !important;
}
:deep(.el-table .danger3) {
  --el-table-tr-bg-color: var(--el-color-danger-light-3) !important;
}
:deep(.el-table .danger2) {
  --el-table-tr-bg-color: var(--el-color-danger-dark-2) !important;
}

:deep(.el-table .info9) {
  --el-table-tr-bg-color: var(--el-color-info-light-9) !important;
}
:deep(.el-table .info8) {
  --el-table-tr-bg-color: var(--el-color-info-light-8) !important;
}
:deep(.el-table .info7) {
  --el-table-tr-bg-color: var(--el-color-info-light-7) !important;
}
:deep(.el-table .info5) {
  --el-table-tr-bg-color: var(--el-color-info-light-5) !important;
}
:deep(.el-table .info3) {
  --el-table-tr-bg-color: var(--el-color-info-light-3) !important;
}
:deep(.el-table .info2) {
  --el-table-tr-bg-color: var(--el-color-info-dark-2) !important;
}
</style>